package com.flowerplus.store.common.structure;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;

import com.flowerplus.store.Logger;
import com.flowerplus.store.R;
import com.flowerplus.store.common.data.utils.ui.ResourcesUtil;
import com.flowerplus.store.common.data.utils.ui.ToastUtil;
import com.flowerplus.store.common.execption.utils.ExceptionHandle;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import javax.inject.Inject;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;


/**
 * Created by z on.
 * Des:权限管理类
 * Date: 2017/3/9
 */

public class PermissionManager {


    private Activity mActivity;
    private ToastUtil mToastUtil;
    private ResourcesUtil mResourcesUtil;
    private RxPermissions mRxPermissions;
    //是否已经打开过
    private boolean isOpen;

    @Inject
    public PermissionManager(Activity activity, ToastUtil toastUtil, ResourcesUtil resourcesUtil) {
        mActivity = activity;
        mToastUtil = toastUtil;
        mResourcesUtil = resourcesUtil;

    }


    /**
     * 检查权限
     *
     * @param action1
     * @param permission
     */
    public Subscription checkPermission(final Action1<Permission> action1, String... permission) {
        return checkPermissionShowNick(action1, "", permission);
    }

    /**
     * 检查权限
     *
     * @param action1
     * @param permission
     */
    public Subscription checkPermissionShowNick(final Action1<Permission> action1, final Action1<Permission> action2,
                                                final String permissionName, String... permission) {
        if (mRxPermissions == null) return null;
        return mRxPermissions.requestEach
                (permission).subscribe(new Action1<Permission>() {
            @Override
            public void call(Permission permission) {
                if (!permission.shouldShowRequestPermissionRationale && !permission.granted) {
                    if (!isOpen) {
                        createDialog(permissionName);
                        if (action2 != null) {
                            action2.call(permission);
                        }
                        isOpen = true;
                    }
                } else if (!permission.granted) {
                    if (!isOpen) {
                        if (action2 != null) {
                            action2.call(permission);
                        }
                        mToastUtil.showShort("请允许 " + mResourcesUtil.getString(R.string.app_name)
                                + " 使用" + permissionName + "权限,否则 " + mResourcesUtil.getString(R.string.app_name)
                                + " 不能正常运行。");
                        isOpen = true;
                    }

                } else {
                    if (!isOpen) {
                        action1.call(permission);
                        isOpen = true;
                    }
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
                String msg = ExceptionHandle.handle(throwable);
                Logger.e("开启权限出现异常");
                mToastUtil.showShort("开启权限时出现异常:" + msg);
            }
        }, new Action0() {
            @Override
            public void call() {
                isOpen = false;
            }
        });
    }

    public Observable<Permission> checkPermissionShowNick(String... permission) {
        if (mRxPermissions == null) return null;
        return mRxPermissions.requestEach
                (permission);
    }

    public Subscription checkPermissionShowNick(final Action1<Permission> action1,
                                                final String permissionName, String... permission) {
        return checkPermissionShowNick(action1, null,
                permissionName, permission);
    }

    /**
     * 不关心是否点了不再询问
     *
     * @param action1
     * @param permissionName
     * @param permission
     * @return
     */
    public Subscription checkPermissionShowNickAll(final Action1<Boolean> action1, final String permissionName, String... permission) {
        if (mRxPermissions == null) return null;
        return mRxPermissions.request
                (permission).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean permission) {
                if (permission) {
                    action1.call(permission);
                } else {
                    mToastUtil.showShort("请允许 " + mResourcesUtil.getString(R.string.app_name)
                            + " 使用" + permissionName + "权限,否则 " + mResourcesUtil.getString(R.string.app_name)
                            + " 不能正常运行。");
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
                Logger.e("开启权限出现异常");
                mToastUtil.showShort("开启权限出现异常");
            }
        }, new Action0() {
            @Override
            public void call() {
                isOpen = false;
            }
        });
    }

    public void setRxPermissions(RxPermissions rxPermissions) {
        mRxPermissions = rxPermissions;
    }


    /**
     * 创建询问是否开启权限dialog
     *
     * @param permissionName
     */
    private void createDialog(String permissionName) {
        new AlertDialog.Builder(mActivity)
                .setTitle("提示")
                .setCancelable(false)
                .setMessage("你已拒绝使用" + permissionName + "权限，是否前往权限管理中心？")
                .setNegativeButton("取消", null)
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri packageURI = Uri.parse("package:" + mActivity.getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        mActivity.startActivity(intent);
                    }
                }).show();
    }
}
